#include <string.h>

#include "usart.h"

#include "ctrl_protocol.h"
#include "ctrl_crc16.h"
#include "oslib.h"

uint8_t wifi_conf_flag = 0;
// extern osMessageQueueId_t UART2_RxQueue;
extern osSemaphoreId_t UART2_RxSema; 
extern char UART2_TaskBuffer[RxBufferSize];
extern osMessageQueueId_t CtrlRecvQueueHandle;

static char RecvTaskBuffer[RxBufferSize];
void _RecvTask(void *argument)
{
    // uint8_t ch;
    ctrl_prot_t *ptr;

    for (;;)
    {
        // osMessageQueueGet(UART2_RxQueue, &ch, NULL, osWaitForever);
        // if (wifi_conf_flag)
        //     OSLIB_Uart_SendData(&huart_major, &ch, 1);
        // ptr = ctrl_recv_char_to_pack(ch);
        // if (ptr != NULL)
        //     osMessageQueuePut(CtrlRecvQueueHandle, &ptr, NULL, 0);
        osSemaphoreAcquire(UART2_RxSema, osWaitForever);
        memcpy(RecvTaskBuffer, UART2_TaskBuffer, 64);
        if (wifi_conf_flag) {
            OSLIB_Uart_SendData(&huart_major, (const uint8_t *)RecvTaskBuffer, 16);
        }
        ptr = (ctrl_prot_t *)RecvTaskBuffer;
        if (ptr->pre != CTRLPROT_PRE || ptr->src != CTRLPROT_SRC_DEVICE)
            continue;
        if (ctrl_crc16((uint8_t *)ptr, 10 + ptr->len) != 0)
            continue;
        osMessageQueuePut(CtrlRecvQueueHandle, &ptr, NULL, 0);
    }
}